package config

import (
	"os"

	"gopkg.in/yaml.v3"
)

type ZipkinConfig struct {
	Enable     bool   `json:"enable"`
	ListenAddr string `json:"listenAddr"` //默认为 DEFAULT_ZIPKIN_LISTEN_ADDR
}

type JaegerConfig struct {
	Enable                  bool   `json:"enable"`
	GrpcListenAddr          string `json:"grpcListenAddr"`          //默认为 DEFAULT_JAEGER_GRPC_LISTEN_ADDR
	HttpListenAddr          string `json:"httpListenAddr"`          //默认为 DEFAULT_JAEGER_HTTP_LISTEN_ADDR
	ThriftCompactListenAddr string `json:"thriftCompactListenAddr"` //默认为 DEFAULT_JAEGER_THRIFT_COMPACT_LISTEN_ADDR
	ThriftBinaryListenAddr  string `json:"thriftBinaryListenAddr"`  //默认为 DEFAULT_JAEGER_THRIFT_BINARY_LISTEN_ADDR
}

type SkywalkingConfig struct {
	Enable         bool   `json:"enable"`
	GrpcListenAddr string `json:"grpcListenAddr"` //默认为 DEFAULT_SKYWALKING_GRPC_LISTEN_ADDR
	HttpListenAddr string `json:"httpListenAddr"` //默认为 DEFAULT_SKYWALKING_HTTP_LISTEN_ADDR
}

type OtlpConfig struct {
	Enable         bool   `json:"enable"`
	GrpcListenAddr string `json:"grpcListenAddr"` //默认为 DEFAULT_OTLP_GRPC_LISTEN_ADDR
	HttpListenAddr string `json:"httpListenAddr"` //默认为 DEFAULT_OTLP_HTTP_LISTEN_ADDR
}

type ServerConfig struct {
	ListenAddr    string           `yaml:"listenAddr"`
	LinkSaasAddr  string           `yaml:"linkSaasAddr"`
	MaxTraceStore uint32           `yaml:"maxTraceStore"`
	ProjectList   []string         `yaml:"project"`
	Zipkin        ZipkinConfig     `json:"zipkin"`
	Jaeger        JaegerConfig     `json:"jaeger"`
	Skywalking    SkywalkingConfig `json:"skywalking"`
	Otlp          OtlpConfig       `json:"otlp"`
}

func (cfg *ServerConfig) SetDefaultValue() {
	if cfg.Zipkin.ListenAddr == "" {
		cfg.Zipkin.ListenAddr = DEFAULT_ZIPKIN_LISTEN_ADDR
	}
	if cfg.Jaeger.GrpcListenAddr == "" {
		cfg.Jaeger.GrpcListenAddr = DEFAULT_JAEGER_GRPC_LISTEN_ADDR
	}
	if cfg.Jaeger.HttpListenAddr == "" {
		cfg.Jaeger.HttpListenAddr = DEFAULT_JAEGER_HTTP_LISTEN_ADDR
	}
	if cfg.Jaeger.ThriftCompactListenAddr == "" {
		cfg.Jaeger.ThriftCompactListenAddr = DEFAULT_JAEGER_THRIFT_COMPACT_LISTEN_ADDR
	}
	if cfg.Jaeger.ThriftBinaryListenAddr == "" {
		cfg.Jaeger.ThriftBinaryListenAddr = DEFAULT_JAEGER_THRIFT_BINARY_LISTEN_ADDR
	}
	if cfg.Skywalking.GrpcListenAddr == "" {
		cfg.Skywalking.GrpcListenAddr = DEFAULT_SKYWALKING_GRPC_LISTEN_ADDR
	}
	if cfg.Skywalking.HttpListenAddr == "" {
		cfg.Skywalking.HttpListenAddr = DEFAULT_SKYWALKING_HTTP_LISTEN_ADDR
	}
	if cfg.Otlp.GrpcListenAddr == "" {
		cfg.Otlp.GrpcListenAddr = DEFAULT_OTLP_GRPC_LISTEN_ADDR
	}
	if cfg.Otlp.HttpListenAddr == "" {
		cfg.Otlp.HttpListenAddr = DEFAULT_OTLP_HTTP_LISTEN_ADDR
	}
}

func LoadServerCfg(fileName string) (*ServerConfig, error) {
	data, err := os.ReadFile(fileName)
	if err != nil {
		return nil, err
	}
	cfg := &ServerConfig{}
	err = yaml.Unmarshal(data, cfg)
	if err != nil {
		return nil, err
	}
	cfg.SetDefaultValue()
	if cfg.MaxTraceStore < 1000 {
		cfg.MaxTraceStore = 1000
	}
	return cfg, nil
}
